package com.ncst.mvcweb.controller;

import com.ncst.mvcweb.entity.User;
import com.ncst.mvcweb.service.UserService;
import com.ncst.mvcweb.vo.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class LoginController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public JsonResult login(String userName, String password, HttpSession session) {
        JsonResult<Object> objectJsonResult = new JsonResult<>();
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            objectJsonResult.setStatus("fail");
            objectJsonResult.setMessage("用户名或密码不能为空");
        }
        else {
            User user = userService.findByUsernameAndPassword(userName, password);
            if (user != null) {
                // 检查用户状态
                if ("1".equals(user.getStatus())) {
                    objectJsonResult.setStatus("fail");
                    objectJsonResult.setMessage("账户已被禁用，请联系管理员");
                } else {
                    objectJsonResult.setStatus("success");
                    objectJsonResult.setMessage("登录成功");
                    objectJsonResult.setData(user);
                    session.setAttribute("loginUser", user);
                }
            }
            else {
                objectJsonResult.setStatus("fail");
                objectJsonResult.setMessage("用户名或密码错误");
            }
        }
        return objectJsonResult;
    }

    @GetMapping("/currentUser")
    public JsonResult getCurrentUser(HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        if (user != null) {
            return new JsonResult("success", "获取成功", user);
        } else {
            return new JsonResult("fail", "用户未登录", null);
        }
    }
}
